//
// Created by martin on 9/12/21.
//

#include "threadio.h"
#include "error.h"
#include "../file/filemanager.h"
#include <pthread.h>
#include <event2/event.h>
#include <fcntl.h>
#include <unistd.h>

static void event_cb(evutil_socket_t fd, short what, void *arg)
{
    char buf[1024];
    ssize_t nread = read(fd, buf, sizeof(buf));
    if (nread < 0) {
        err_ret("read error for thread io event_cb");
        return;
    }

    buf[nread] = 0; /* for printable string */


}

void *threadio_main(void *arg)
{
    int fd = *(int *)arg;

    struct event_base *base = event_base_new();
    if (!base) {
        err_sys("event_base_new error for threadio_main");
    }

    struct event *ev = event_new(base, fd, EV_READ, event_cb, NULL);
    event_base_dispatch(base);

    event_base_free(base);
    return NULL;
}

int threadio_init()
{
    int fds[2];
    if (socketpair(AF_INET, SOCK_STREAM, 0, fds) < 0) {
        err_sys("socketpair error for thread_init");
    }

    pthread_t tid;
    tid = pthread_create(&tid, NULL, threadio_main, &fds[0]);
    if (tid != 0) {
        err_exit(errno, "pthread_create error for threadio_init");
    }
    return 0;
}